package com.lz.service.impl;

import com.lz.dao.ProductInfoDao;
import com.lz.entity.CartQuery;
import com.lz.entity.ProductInfo;
import com.lz.enums.ProductStatusEnum;
import com.lz.enums.ResultEnum;
import com.lz.exception.SellException;
import com.lz.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品信息业务
 * Created by lz on 2018/8/10.
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService{

    @Autowired
    private ProductInfoDao productInfoDao;

    /** 根据id查询 */
    @Override
    public ProductInfo findOne(String id) {
        return productInfoDao.findOne(id);
    }

    /** 查询上架产品 */
    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoDao.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    /** 所有产品分页 */
    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return productInfoDao.findAll(pageable);
    }

    @Override
    @Transactional
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoDao.save(productInfo);
    }

    /**
     * 增加库存
     * @param cartQueryList
     */
    @Override
    @Transactional
    public void increaseStock(List<CartQuery> cartQueryList) {
        for (CartQuery cartQuery : cartQueryList) {
            ProductInfo one = productInfoDao.findOne(cartQuery.getProductId());
            if (one == null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer i = one.getProductStock() + cartQuery.getProductQuantity();
            one.setProductStock(i);
            productInfoDao.save(one);
        }
    }

    /**
     * 减库存
     * @param cartQueryList 购物车
     */
    @Override
    @Transactional
    public void decreaseStock(List<CartQuery> cartQueryList) {
        for (CartQuery cartQuery : cartQueryList) {
            ProductInfo one = productInfoDao.findOne(cartQuery.getProductId());
            if (one == null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer i = one.getProductStock() - cartQuery.getProductQuantity();
            if (i < 0){
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            one.setProductStock(i);
            productInfoDao.save(one);
        }
    }
}
